package team.yidong.fenda.serviceImpl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.DTO.GuahaoHistoryDTO;
import team.yidong.fenda.DTO.GuahaoHistoryForSysDTO;
import team.yidong.fenda.DTO.GuahaoMsgDTO;
import team.yidong.fenda.entity.*;
import team.yidong.fenda.repository.*;
import team.yidong.fenda.service.GuahaoHistoryService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by xuanlong on 2018/3/21.
 */
@Service
public class GuahaoHistoryServiceImpl implements GuahaoHistoryService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    GuahaoHistoryRepository guahaoHistoryRepository;
    @Autowired
    MasterRepository masterRepository;
    @Autowired
    HospitalDepartmentRepository hospitalDepartmentRepository;
    @Autowired
    HospitalRepository hospitalRepository;
    @Autowired
    GuaHaoRepository guaHaoRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    HospitalScheduleRepository hospitalScheduleRepository;

    @Transactional
    @Override
    public JSONObject addGuahaoHistory(String out_trade_no, String openId, String name, String idCard, String phoneNumber, String guahaoDate, String caseCard, String moneyNum, Integer masterId) {
        GuahaoHistory guahaoHistory = new GuahaoHistory();
        HospitalDepartment hospitalDepartment = hospitalDepartmentRepository.findOne(masterRepository.findOne(masterId).getHospitalDepartmentId());
        Hospital hospital = hospitalRepository.findOne(hospitalDepartment.getHospitalId());
        guahaoHistory.setOutTradeNo(out_trade_no);
        guahaoHistory.setOpenId(openId);
        guahaoHistory.setName(name);
        if (caseCard != null && !caseCard.equals("")) {
            guahaoHistory.setCaseCard(caseCard);
        }
        if (idCard != null && !idCard.equals("")) {
            guahaoHistory.setIdCard(idCard);
        }

        guahaoHistory.setGuahaoDate(guahaoDate);
        guahaoHistory.setMasterId(masterId);
        guahaoHistory.setDepartmentId(hospitalDepartment.getId());
        guahaoHistory.setPhoneNumber(phoneNumber);
        guahaoHistory.setHospitalId(hospital.getId());
        long nowDate = new Date().getTime();
        String guahaoNum = Integer.toHexString((int) nowDate);
        guahaoHistory.setGuahaocardNum(guahaoNum);
        guahaoHistory.setStatus("weijiaofei");


        /*
        计算当前挂号为第几人，查找第几人返回的信息
         */
        List<GuahaoHistory> guahaoHistoryList = guahaoHistoryRepository.findByGuahaoDate(guahaoDate);
        Integer peopleNum = new Integer(1);
        if (guahaoHistoryList != null) {
            peopleNum = guahaoHistoryList.size() + 1;
        }
        logger.info(peopleNum + "******************");
        if (guahaoDate.substring(11, 13).equals("11")) {

            HospitalSchedule hospitalSchedule = hospitalScheduleRepository.findByPeopleNumAndDayTime(peopleNum, "AM");
            if (hospitalSchedule == null || hospitalSchedule.getStatus().equals("off")) {
                logger.info("1111******");
                GuahaoMsgDTO guahaoMsgDTO = new GuahaoMsgDTO();
                guahaoMsgDTO.setGuahaoNum(guahaoNum);
                guahaoMsgDTO.setMsg("请打电话咨询就诊时间");
                guahaoHistory.setMsg("请打电话咨询就诊时间");
                guahaoHistoryRepository.save(guahaoHistory);
                Guahao guahao = guaHaoRepository.findByGhDateAndMasterId(guahaoDate, masterId);
                guahao.setGuahaoNum(guahao.getGuahaoNum() - 1);
                guaHaoRepository.save(guahao);
                return JSONObject.fromObject(guahaoMsgDTO);


            } else {
                logger.info("时间:" + guahaoDate);
                GuahaoMsgDTO guahaoMsgDTO = new GuahaoMsgDTO();
                guahaoMsgDTO.setGuahaoNum(guahaoNum);
                guahaoMsgDTO.setMsg(hospitalSchedule.getMsg());
                guahaoHistory.setMsg(hospitalSchedule.getMsg());
                guahaoHistoryRepository.save(guahaoHistory);
                Guahao guahao = guaHaoRepository.findByGhDateAndMasterId(guahaoDate, masterId);
                guahao.setGuahaoNum(guahao.getGuahaoNum() - 1);
                guaHaoRepository.save(guahao);
                return JSONObject.fromObject(guahaoMsgDTO);
            }

        } else {
            logger.info("3333******");
            HospitalSchedule hospitalSchedule = hospitalScheduleRepository.findByPeopleNumAndDayTime(peopleNum, "PM");
            if (hospitalSchedule == null || hospitalSchedule.getStatus().equals("off")) {
                GuahaoMsgDTO guahaoMsgDTO = new GuahaoMsgDTO();
                guahaoMsgDTO.setGuahaoNum(guahaoNum);
                guahaoMsgDTO.setMsg("请打电话咨询就诊时间");
                guahaoHistory.setMsg("请打电话咨询就诊时间");
                guahaoHistoryRepository.save(guahaoHistory);
                Guahao guahao = guaHaoRepository.findByGhDateAndMasterId(guahaoDate, masterId);
                guahao.setGuahaoNum(guahao.getGuahaoNum() - 1);
                guaHaoRepository.save(guahao);
                return JSONObject.fromObject(guahaoMsgDTO);


            } else {
                logger.info("4444******");
                GuahaoMsgDTO guahaoMsgDTO = new GuahaoMsgDTO();
                guahaoMsgDTO.setGuahaoNum(guahaoNum);
                guahaoMsgDTO.setMsg(hospitalSchedule.getMsg());
                guahaoHistory.setMsg(hospitalSchedule.getMsg());
                guahaoHistoryRepository.save(guahaoHistory);
                Guahao guahao = guaHaoRepository.findByGhDateAndMasterId(guahaoDate, masterId);
                guahao.setGuahaoNum(guahao.getGuahaoNum() - 1);
                guaHaoRepository.save(guahao);
                return JSONObject.fromObject(guahaoMsgDTO);
            }
        }

    }


    @Override
    public JSONArray findGuahaoHistory(String openId) {
        List<GuahaoHistory> guahaoHistoryList = guahaoHistoryRepository.findByOpenIdOrderByOrderDateDesc(openId);
        List<GuahaoHistoryDTO> guahaoHistoryDTOList = new ArrayList<>();
        for (GuahaoHistory guahaoHistory : guahaoHistoryList) {
            GuahaoHistoryDTO guahaoHistoryDTO = new GuahaoHistoryDTO();
            guahaoHistoryDTO.setGuahaoHistoryId(guahaoHistory.getId());
            guahaoHistoryDTO.setMoneyNum(Integer.valueOf(guahaoHistory.getMoneyNum()));
            guahaoHistoryDTO.setMasterName(masterRepository.findOne(guahaoHistory.getMasterId()).getName());
            guahaoHistoryDTO.setDepartmentName(hospitalDepartmentRepository.findOne(masterRepository.findOne(guahaoHistory.getMasterId()).getHospitalDepartmentId()).getDepartmentName());
            guahaoHistoryDTO.setGuahaoCardNum(guahaoHistory.getGuahaocardNum());
            guahaoHistoryDTO.setYuyueDate(guahaoHistory.getGuahaoDate());
            guahaoHistoryDTO.setName(guahaoHistory.getName());
            guahaoHistoryDTO.setIdCard(guahaoHistory.getIdCard());
            guahaoHistoryDTO.setMsg(guahaoHistory.getMsg());
            guahaoHistoryDTOList.add(guahaoHistoryDTO);

        }
        return JSONArray.fromObject(guahaoHistoryDTOList);

    }


    @Transactional
    @Override
    public void finishiGuahaoHistory(String out_trade_no, String endTime, String appid, Integer moneyNum) {
        GuahaoHistory guahaoHistory = guahaoHistoryRepository.findByOutTradeNo(out_trade_no);
        guahaoHistory.setOrderDate(endTime);
        guahaoHistory.setAppId(appid);
        guahaoHistory.setMoneyNum(moneyNum.toString());
        guahaoHistory.setStatus("yijiaofei");
        guahaoHistoryRepository.save(guahaoHistory);
    }

    @Override
    public JSONArray findGuahaoHistoryForSys(Integer hospitalId, Integer departmentId, String jiaofeiDate1, String jiaofeiDate2, String yuyueDate1, String yuyueDate2, Integer moneyNum, String guahaoNum, String idCard, String phoneNum) {
        List<GuahaoHistory> guahaoHistoryList = guahaoHistoryRepository.findAll(new Specification<GuahaoHistory>() {
            @Override
            public Predicate toPredicate(Root<GuahaoHistory> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (hospitalId != null && !hospitalId.equals("")) {
                    Predicate p = criteriaBuilder.equal(root.get("hospitalId").as(Integer.class), hospitalId);
                    predicateList.add(p);
                }
                if (departmentId != null && !departmentId.equals("")) {
                    Predicate p = criteriaBuilder.equal(root.get("departmentId").as(Integer.class), departmentId);
                    predicateList.add(p);
                }
                if (jiaofeiDate1 != null && !jiaofeiDate1.equals("")) {
                    Predicate p = criteriaBuilder.greaterThanOrEqualTo(root.get("orderDate").as(String.class), jiaofeiDate1);
                    predicateList.add(p);
                }
                if (jiaofeiDate2 != null && !jiaofeiDate2.equals("")) {
                    Predicate p = criteriaBuilder.lessThanOrEqualTo(root.get("orderDate").as(String.class), jiaofeiDate2);
                    predicateList.add(p);
                }
                if (yuyueDate1 != null && !yuyueDate1.equals("")) {
                    Predicate p = criteriaBuilder.greaterThanOrEqualTo(root.get("guahaoDate").as(String.class), yuyueDate1);
                    predicateList.add(p);
                }
                if (yuyueDate2 != null && !yuyueDate2.equals("")) {
                    Predicate p = criteriaBuilder.lessThanOrEqualTo(root.get("guahaoDate").as(String.class), yuyueDate2);
                    predicateList.add(p);
                }
                if (moneyNum != null && !moneyNum.equals("")) {
                    Predicate p = criteriaBuilder.equal(root.get("moneyNum").as(Integer.class), moneyNum);
                    predicateList.add(p);
                }
                if (guahaoNum != null && !guahaoNum.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("guahaocardNum").as(String.class), "%" + guahaoNum + "%");
                    predicateList.add(p);
                }
                if (idCard != null && !idCard.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("idCard").as(String.class), "%" + idCard + "%");
                    predicateList.add(p);
                }
                if (phoneNum != null && !phoneNum.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("phoneNumber").as(String.class), "%" + phoneNum + "%");
                    predicateList.add(p);
                }
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        });
        List<GuahaoHistoryForSysDTO> guahaoHistoryDTOList = new ArrayList<>();
        for (GuahaoHistory guahaoHistory : guahaoHistoryList) {
            GuahaoHistoryForSysDTO guahaoHistoryDTO = new GuahaoHistoryForSysDTO();
            HospitalDepartment hospitalDepartment = hospitalDepartmentRepository.findOne(guahaoHistory.getDepartmentId());
            guahaoHistoryDTO.setHospitalName(hospitalRepository.findOne(hospitalDepartment.getHospitalId()).getName());
            guahaoHistoryDTO.setGuahaoHistoryId(guahaoHistory.getId());
            guahaoHistoryDTO.setMoneyNum(guahaoHistory.getMoneyNum());
            guahaoHistoryDTO.setMasterName(masterRepository.findOne(guahaoHistory.getMasterId()).getName());
            guahaoHistoryDTO.setDepartmentName(hospitalDepartmentRepository.findOne(guahaoHistory.getDepartmentId()).getDepartmentName());
            guahaoHistoryDTO.setGuahaoCardNum(guahaoHistory.getGuahaocardNum());
            guahaoHistoryDTO.setYuyueDate(guahaoHistory.getGuahaoDate());
            guahaoHistoryDTO.setName(guahaoHistory.getName());
            guahaoHistoryDTO.setJiaofeiDate(guahaoHistory.getOrderDate());
            guahaoHistoryDTO.setPhoneNumber(guahaoHistory.getPhoneNumber());
            guahaoHistoryDTO.setIdCard(guahaoHistory.getIdCard());
            guahaoHistoryDTO.setMsg(guahaoHistory.getMsg());
            guahaoHistoryDTO.setUserName(userRepository.findByUserOpenId(guahaoHistory.getOpenId()).getName());
            guahaoHistoryDTOList.add(guahaoHistoryDTO);
        }
        return JSONArray.fromObject(guahaoHistoryDTOList);
    }
}
